#if DEBUG_VERSION
if (!dafos) {
  throw new Error("Dafos namespace not found!");
}
#endif


//Stores the string values to display in the output field
var output_buffer = [];

 /**
 * Returns the supplied arguments object as an array
 * @param {Object} args Function.arguments object
 * @return {Array} An array corresponding to the items in args
 */
function getArgsAsArray(args) {
  var result = [];
  for (var i=0; i < args.length; i++) {
    result.push(args[i]);
  }
  return result;
};

/**
 * Method to print data to this application's output container
 * @param args Takes a variable number of arguments.  Each argument
 *   is printed to the output.
 */
function output() {
  var args = getArgsAsArray(output.arguments);
  var out_element = document.getElementById("output");
  if (window.console && console.log) {
    console.log("output", args);
  }
  output_buffer.push(args.join(" "));
  while (output_buffer.length > 400) {
    output_buffer.shift();
  }
  out_element.innerHTML = output_buffer.join("<br />");
  out_element.scrollTop = out_element.scrollHeight;
  if (out_element.style.display == "none") {
    out_element.style.display = "block";
  }
  gadgets.window.adjustHeight();
};

/**
 * Clears the output container
 */
function cls() {
  output_buffer = [];
  var out_element = document.getElementById("output");
  out_element.innerHTML = "";
  out_element.style.display = "none";
  gadgets.window.adjustHeight();
};


dafos.onCodeTabActivated = function() {
  TRACK("tab/code");
  RESIZE();
};


dafos.onOpenSocialData = function(data) {
  LOG("[onOpenSocialData]", "data", data);
  dafos.ui.hideLoading("opensocial");
  if (dafos.opensocial.viewerIsOwner()) {
    LOG("Viewer is Owner");
    SEGMENT("user/viewer==owner");
  } else {
    LOG("Viewer is not Owner");
    SEGMENT("user/viewer!=owner");
  }
  SEGMENT("container/" + opensocial.getEnvironment().getDomain());
  dafos.initCallback.callback();  
};

dafos.onLastLoadedSet = function(data, qos) {
  LOG("[dafos.onLastLoadedSet]", data, qos);  
};

dafos.onViewerSettingsAvailable = function(data, qos) {
  LOG("[dafos.onPersistenceData]", data, qos);  
  var default_tab = "Code";
  
#ifdef HELPTAB
  //TODO: Change the app to load separate files for different views and
  //put this into another file
  if (dafos.viewname != "profile" && dafos.viewname != "home") {
    var viewerid = data.viewer && data.viewer.getId();
    if (viewerid) {
      var lastloaded = data.data && 
                       data.data[viewerid] &&
                       data.data[viewerid]["lastloaded"];
      if (!lastloaded) {
        LOG("No last loaded value, setting default tab to Help");
        default_tab = "Help";
        e34.$("helptab-context-message").show();
        SEGMENT("user/new"); 
      } else {
        e34.$("helptab-context-message").hide();
        SEGMENT("user/repeat"); 
      }
    }
  }
#endif

  new quikos().startRequest()
      .setData("lastloaded", new Date().getTime(), "setdata")
      .fetchData(quikos.idspec.VIEWER, "fetchdata")
      .sendRequest(dafos.onLastLoadedSet);
  
  dafos.createTabs(default_tab);
};

dafos.createTabs = function(default_tab) {
  LOG("[dafos.createTabs]", "default tab is", default_tab);
  
  dafos.tabs = new gadgets.TabSet("dafos", default_tab, dafos.wrap);
  dafos.tabs.alignTabs("left", 10);
  
  dafos.tabs.addTab("Code", {
     contentContainer: document.getElementById("codetab"), 
     callback: dafos.onCodeTabActivated, 
     tooltip: "Write and test JavaScript code" 
  });
  dafos.codetab = new dafos.CodeTab(dafos.wrap, dafos.ui);

  if (dafos.viewname != "profile" && dafos.viewname != "home") {
#if NEWSTAB
    dafos.tabs.addTab("News", {
       contentContainer: document.getElementById("newstab"), 
       callback: dafos.onNewsTabActivated, 
       tooltip: "OpenSocial news" 
    });
#endif

#if TOOLSTAB
    dafos.tabs.addTab("Tools", {
       contentContainer: document.getElementById("toolstab"), 
       callback: dafos.onToolsTabActivated, 
       tooltip: "Developer tools" 
    });
#endif

#if FRIENDSTAB
    dafos.tabs.addTab("Friends", {
       contentContainer: document.getElementById("friendstab"),
       callback: dafos.onFriendsTabActivated,
       tooltop: "Samples from your friends"
    });
#endif

#if SNIPPETSTAB
    dafos.tabs.addTab("Samples", {
       contentContainer: document.getElementById("snippetstab"),
       callback: dafos.onSnippetsTabActivated,
       tooltop: "Code snippets to help you get started"
    });
#endif

#if STATETAB
    dafos.tabs.addTab("Data Viewer", {
       contentContainer: document.getElementById("statetab"), 
       callback: dafos.onStateTabActivated, 
       tooltip: "State viewer" 
    });
#endif

#if EXPORTTAB
    dafos.tabs.addTab("Export XML", {
       contentContainer: document.getElementById("exporttab"), 
       callback: dafos.onExportTabActivated, 
       tooltip: "Export an XML file" 
    });
#endif

#if HELPTAB
    dafos.tabs.addTab("Help", {
      contentContainer: document.getElementById("helptab"),
      callback: dafos.onHelpTabActivated,
      tooltop: "Help"
    });
#endif
  } else {
    var canvasview = gadgets.views.getSupportedViews()["canvas"];
    if (canvasview) {
      dafos.tabs.addTab("Canvas view", {
        callback: function() { 
          gadgets.views.requestNavigateTo(canvasview); 
        },
        tooltop: "Navigate to the canvas view"
      });  
    }
  }
};


dafos.init = function() {
  LOG("[dafos.init]");
};

dafos.onError = function(msg, url, line) {
  dafos.ui.setError(msg);
  LOG("[onError]", msg, url, line);
};

//When the application is loaded, run this
gadgets.util.registerOnLoadHandler(function() {
  dafos.initCallback = new ark.AggregateCallback(dafos.init);
  dafos.cansave = false;
  dafos.wrap = document.getElementById("wrap");
  dafos.ui = new dafos.GadgetUI(dafos.wrap);
  dafos.opensocial = new dafos.OpenSocial();
  dafos.viewname = gadgets.views.getCurrentView().getName();
  onerror = dafos.onError;
  
  //Get OpenSocial data
  dafos.ui.showLoading("opensocial");
  dafos.initCallback.getCallback();
  dafos.opensocial.getOpenSocialData("*", dafos.onOpenSocialData);
  
  //TODO: Migrate OpenSocial calls to quikos
  //Request persistence data so we can check for certain keys
  new quikos().startRequest()
      .fetchPerson(quikos.id.VIEWER, "viewer")
      .fetchData(quikos.idspec.VIEWER, "data")
      .sendRequest(dafos.onViewerSettingsAvailable);
});